/**
 * @author litianyuan
 * @date   2014-12-18
 */
var notNull = function(e){
    return e!=null && e && e!="";
};

var uniqArr = function(arr){
    if (arr) {
        return arr.filter(function(item, pos, self){
            return self.indexOf(item) == pos;
        });
    };
};

var getSubtimes = function (dataArr, typeArr) {
    var result = {};
    angular.forEach(dataArr, function (value, idx) {
      if (typeArr[value]) {
          this[value] = typeArr[value];
      }
    }, result);
    return result;
}

//判断空对象的方法：
var isEmptyObject =  function( obj ) {
  for ( var x in obj ) {
    return false;
  }
  return true;
}
//判断对象属性的数量
var objectCount = function (obj) {
  var cnt = 0;
  angular.forEach(obj, function (data, key) {
      cnt++;
  });

  return cnt;
}

//获取category对应的共享活动
getShareCategory = function (category) {
  var result = [];
  var arr = sharedActivitys[category];
  for (var i = 0; arr && i < arr.length; i++) {
    var obj = {};
    obj.id = arr[i];
    obj.name = allRuleCategory[arr[i]];
    result.push(obj);
  }
  return result;
}

//转换对象到数组，类似于Object.keys()
objectKeys = function (obj) {
  var res = [];
  angular.forEach(obj, function (data, idx) {
    this.push(idx);
  }, res);
  return res;
}

//cb回调函数，对数组元素使用使用，类似于Array.map();
arrayMap = function (arr, cb) {
    var tmp = [];
    if (typeof cb === "function") {
      angular.forEach(arr, function (data, idx) {
        var t = data;
        t = cb(data);
        this.push(t)
      }, tmp);
    }else{
      tmp = arr;
    }
    return tmp;
}

//filter过滤函数，对数组元素进行过滤，类似Array.filter()
arrayFilter = function (arr, filter) {
  var tmp = [];
  if (typeof filter === "function") {
    angular.forEach(arr, function (data, idx) {
      filter(data) && this.push(data);
    }, tmp);
  }else{
    tmp = arr;
  }
  return tmp;
}

angular.module('app').config(appRouteConfig);

function appRouteConfig($routeProvider) { //路由规则
        $routeProvider.when('/shops', {
                templateUrl: "admin/shops/index.html",
                controller: "ShopsCtr"
            }) //商店首页
            .when('/shops/add', {
                templateUrl: "admin/shops/add.html",
                controller: "ShopsAddCtr"
            }) //门店添加
            .when('/shops/add/:shopId', {
                templateUrl: "admin/shops/add.html",
                controller: "ShopsAddreturnCtr"
            }) //门店添加返回
            .when('/shops/add2/:shopId', {
                templateUrl: "admin/shops/add2.html",
                controller: "ShopsAdd2Ctr"
            }) //门店添加2
            .when('/shops/add3/:shopId', {
                templateUrl: "admin/shops/add3.html",
                controller: "ShopsAdd3Ctr"
            }) //门店添加3
            .when('/shops/show/:shopId', {
                templateUrl: "admin/shops/show.html",
                controller: "ShopsShowCtr"
            }) //门店详情
            .when('/staff', {
                templateUrl: "admin/Staff/index.html",
                controller: "StaffCtr"
            }) //员工管理
            .when('/staff/show/:shopId', {
                templateUrl: "admin/Staff/show.html",
                controller: "StaffShowCtr"
            }) //门店员工展示
            .when('/staff/staffadd/:shopId', {
                templateUrl: "admin/Staff/staffadd.html",
                controller: "StaffaddCtr"
            }) //添加员工
            .when('/staff/staffedit/:guestid', {
                templateUrl: "admin/Staff/staffedit.html",
                controller: "StaffeditCtr"
            }) //修改员工
            .when('/staff/keeperedit/:guestid', {
                templateUrl: "admin/Staff/keeperedit.html",
                controller: "StaffeditCtr"
            }) //店长编辑
            .when('/staff/keeperadd/:shopId', {
                templateUrl: "admin/Staff/keeperadd.html",
                controller: "StaffaddCtr"
            }) //添加店长
            .when('/staff/password/:guestid', {
                templateUrl: "admin/Staff/password.html",
                controller: "passwordCtr"
            }) //重置密码
            .when('/password', {
                templateUrl: "my/password.html",
                controller: "edit_passwordCtr"
            }) //修改自己的密码
            .when('/rule', {
                templateUrl: "admin/rule/index.html",
                controller: "RuleCtr"
            }) //活动列表
            .when('/rule/add', {
                templateUrl: "admin/rule/add.html",
                controller: "RuleAddCtr"
            }) //添加活动第一步
            .when('/rule/add2/:activityid', {
                templateUrl: "admin/rule/add2.html",
                controller: "RuleAdd2Ctr"
            }) //添加活动第二部
            .when('/rule/edit/:activityid', {
                templateUrl: "admin/rule/ruleedit.html",
                controller: "RuleAddCtr"
            }) //修改活动
            .when('/rule/edit2/:activityid', {
                templateUrl: "admin/rule/ruleedit2.html",
                controller: "RuleAdd2Ctr"
            }) //修改活动
            .when('/rule/edit3/:activityid', {
                templateUrl: "admin/rule/ruleedit3.html",
                controller: "RuleAdd3Ctr"
            }) //修改活动
            .when('/rule/menber', {
                templateUrl: "admin/rule/menber.html",
                controller: "RuleMemberCtr"
            }) //会员规则
            .when('/rule/coupon', {
                templateUrl: "admin/rule/coupon.html",
                controller: "RuleCouponCtr"
            }) //会员规则
            .when('/customer/charge/:userId', {
                templateUrl: "admin/customer/charge.html",
                controller: "CustomerChargeCtr"
            }) //会员充值
            .when('/customer/point/:userId', {
                templateUrl: "admin/customer/point.html",
                controller: "CustomerPoicustomerntCtr"
            }) //顾客积分
            .when('/customer/coupon/:userId', {
                templateUrl: "admin/customer/coupon.html",
                controller: "CustomerCouponCtr"
            }) //顾客发券
            .when('/customer/add', {
                templateUrl: "admin/customer/add.html",
                controller: "CustomerAddCtr"
            }) //顾客发券
            .when('/customer', {
                templateUrl: "admin/customer/index.html",
                controller: "CustomerCtr"
            }) //顾客
            .when('/test', {
                templateUrl: "test.html",
                controller: "TestCtr"
            }) //设备管理
            .when('/devices', {
                templateUrl: "admin/devices/index.html",
                controller: "DevicesCtr"
            })//test
            .otherwise({
                redirectTo: "/shops"
            }); //其他路径
    }
    /*------------------------------------------------------------------*/
app.controller('ShopsCtr', function($scope, $location, $http) { //shoplist over
    $scope.config.breadset = [{ //
        name: "门店管理"
    }, {
        name: "门店列表"
    }]; //面包屑
    $scope.authed = {
        "1001": "未认证",
        "1002": "已认证",
        "1003": "认证审核中",
        "1004": "关闭审核中",
        "1005": "关闭",
    };
    $http.get(basicUrl + "/shops").then(function(e) {
        if (e.data.code != 200) $location.path("/shops/add");
        $scope.shops = {
            list: e.data.result
        };
    });
});
/*------------------------------------------------------------------*/
app.controller('ShopsAddCtr', function($scope, $location) {
        $scope.config.breadset = [{ //
            name: "门店管理",
            href: indexUrl + "/admin.html#/shops"
        }, {
            name: "添加门店"
        }]; //面包屑
        $scope.posts = {};
        $scope.shopType = [{
            code: 1001,
            text: '连锁店'
        }, {
            code: 1002,
            text: '自营店'
        }, {
            code: 1003,
            text: '加盟店'
        }];
        $scope.posts.shopType = $scope.shopType[0].code;
        $scope.areaJson1 = ajaxSendFn({}, "/dict/area", "GET").result;
        $scope.area1change = function() { //
            $scope.areaJson2 = ajaxSendFn({}, "/dict/area?code=" + $scope.area.area1, "GET").result || [];
            $scope.area.area2 = $scope.areaJson2[0] && $scope.areaJson2[0].code;
            $scope.areaJson3 = $scope.area.area2 ? (ajaxSendFn({}, "/dict/area?code=" + $scope.area.area2, "GET").result || []) : false;
            $scope.posts.area = ($scope.areaJson3[0] && $scope.areaJson3[0].code) || ($scope.areaJson2[0] && $scope.areaJson2[0].code) || ($scope.areaJson1[0] && $scope.areaJson1[0].code);
        };
        $scope.area2change = function() { //
            $scope.areaJson3 = ajaxSendFn({}, "/dict/area?code=" + $scope.area.area2, "GET").result || [];
            $scope.posts.area = ($scope.areaJson3[0] && $scope.areaJson3[0].code) || ($scope.areaJson2[0] && $scope.areaJson2[0].code);
        };
        $scope.postSend = function() { //
            var sendJson = JSON.stringify($scope.posts);
            var postsend = ajaxSendFn(sendJson, "/shops/shop", "POST", 1);
            if (postsend.code == 200) {
                $location.path("/shops/add2/" + postsend.result.id);
            } else { //
                $scope.config.modalContent = errorCodeJson[postsend.code];
                $(".modal").modal("show");
                return;
            }
        };
    })
    /*------------------------------------------------------------------*/
app.controller('ShopsAddreturnCtr', function($scope, $location, $routeParams) {
        $scope.config.breadset = [{ //
            name: "门店管理",
            href: indexUrl + "/admin.html#/shops"
        }, {
            name: "添加门店"
        }]; //面包屑
        shopTypes = ajaxSendFn({}, "/dict/SHOP_TYPE/item", "GET").result;
        $scope.shopget = ajaxSendFn({}, "/shops/shop/" + $routeParams.shopId, "GET").result.shop;
        $scope.shopType = shopTypes;
        $scope.posts = { //
            shopCode: $scope.shopget.shopCode,
            name: $scope.shopget.name,
            shopType: $scope.shopget.shopType,
            area: $scope.shopget.area,
            tel: $scope.shopget.tel,
            id: $scope.shopget.id
        };
    })
    /*------------------------------------------------------------------*/
app.controller('ShopsAdd2Ctr', function($scope, $location, $routeParams) {
        $scope.config.breadset = [{ //
            name: "门店管理",
            href: indexUrl + "/admin.html#/shops"
        }, {
            name: "添加店长"
        }]; //面包屑
        $scope.posts = {};
        $scope.postSend = function() { //
            sendJsons = {
                "name": $scope.posts.name,
                "nickname": $scope.posts.nickname,
                "password": hex_md5($scope.posts.password),
                "shopId": $routeParams.shopId,
                "roleType": "K"
            };
            for (var x in sendJsons) {
                if (sendJsons[x] == "" || !sendJsons[x] || sendJsons == null) { //
                    delete sendJsons[x];
                }
            }
            sendJson = JSON.stringify(sendJsons);
            postsend = ajaxSendFn(sendJson, constUrlDict["staff"], "POST", 1);
            if (postsend.code == 200) {
                $location.path("/shops/add3/" + $routeParams.shopId);
            } else { //
                $scope.modalFn("服务器繁忙,请稍后再试!");
                $("#modal").modal("show");
                return;
            }
        };
        $scope.reshpwd = function() {
            console.log($scope.staffadd_form)
            if ($scope.repassword == $scope.posts.password) { //
                $scope.staffadd_form.repassword.$error.pattern = false;
            } else { //
                $scope.staffadd_form.repassword.$error.pattern = true;
            }
        }
    })
    /*------------------------------------------------------------------*/
app.controller('ShopsAdd3Ctr', function($scope, $location, $routeParams) {
        $scope.config.breadset = [{ //
            name: "门店管理",
            href: indexUrl + "/admin.html#/shops"
        }, {
            name: "添加完成"
        }]; //面包屑
        shopsget = ajaxSendFn({}, "/shops/shop/" + $routeParams.shopId, "GET");
        $scope.shopshow = shopsget.code == 200 ? shopsget.result : false;
    })
    /*------------------------------------------------------------------*/
app.controller('ShopsShowCtr', function($scope, $routeParams, $http) {
        $scope.shopId = $routeParams.shopId;
        $scope.config.breadset = [{ //
            name: "门店管理",
            href: indexUrl + "/admin.html#/shops"
        }, {
            name: "门店状态"
        }]; //面包屑
        $scope.shopshow = {
            result: {
                businesstime: {}
            }
        };
        $scope.bussniessTime = {
            1001: "早市",
            1002: "午市",
            1003: "下午茶",
            1004: "晚市",
            1005: "宵夜"
        };
        $http.get(basicUrl + "/shops/shop/" + $routeParams.shopId).then(function(data) { //获取门店基本信息
            $scope.shopshow.result = data.data.result || {};
            $scope.shopshow.result.shopType = shopTypeJson[$scope.shopshow.result.shopType];
            if (!$scope.shopshow.result.latitude || !$scope.shopshow.result.longitude) return;
            $scope.shopshow.map = "http://restapi.amap.com/v3/staticmap?zoom=16&size=180*120&markers=-1,http://api.amap.com/Public/imgbox/static/8.png,0:" + $scope.shopshow.result.longitude + "," + $scope.shopshow.result.latitude + "&key=ee95e52bf08006f63fd29bcfbcf21df0";
        })
        $scope.deleteShopFn = function() {
            if (confirm("是否确定申请关闭?")) {
                $http.post(basicUrl + "/shops/" + $routeParams.shopId).success(function(data) {
                    $scope.shopshow.result.state = "1004";
                    if (data.code == 200) alert("申请关闭成功！");
                    else errorMsg(data);
                })
            }
        }
    })
    /*------------------------------------------------------------------*/
app.controller('StaffCtr', function($scope, $http) {
        $scope.config.breadset = [{ //
            name: "员工管理",
            href: indexUrl + "/admin.html#/staff"
        }, {
            name: "员工列表"
        }]; //面包屑
        $http.get(basicUrl + constUrlDict["staffs-base"]).success(function(date) {
            $scope.staffs = date.result || []
        })
    })
    /*------------------------------------------------------------------*/
app.controller('StaffShowCtr', function($scope, $location, $routeParams) {
        $scope.user = {};
        $scope.user.list = {
            keeper: [],
            staffs: []
        };
        $scope.user.shopId = $routeParams.shopId
        $scope.config.breadset = [{ //
            name: "员工管理",
            href: indexUrl + "/admin.html#/staff"
        }, {
            name: "员工列表"
        }]; //面包屑
        $scope.shopget = ajaxSendFn({}, "/shops/shop/" + $routeParams.shopId, "GET").result;
        $scope.user.get = ajaxSendFn({}, constUrlDict["staffs-shop"] + "?shopId=" + $routeParams.shopId, "GET").result;
        $scope.user.get = $scope.user.get ? $scope.user.get : "";
        for (var i = 0; i < $scope.user.get.length; i++) {
            if ($scope.user.get[i].roleType == "K") { //
                $scope.user.list.keeper = $scope.user.get[i];
            } else { //
                $scope.user.list.staffs.push($scope.user.get[i]);
            }
        };
        $scope.staffDelFn = function(index) { //
            if (!confirm("一旦删除将不可恢复，是否确认删除？")) return false;
            staffDelRe = ajaxSendFn({}, constUrlDict["staffs-base"] +"/" + $scope.user.list.staffs[index].id, "POST");
            if (staffDelRe.code == 200) { //
                $scope.user.list.staffs.splice(index, 1);
                alert("删除成功");
            } else { //
                errorMsg(staffDelRe);
            }
        }
        $scope.keepperDelFn = function() { //
            if (!confirm("一旦删除将不可恢复，是否确认删除？")) return false;
            staffDelRe = ajaxSendFn({}, constUrlDict["staffs-base"]+ "/" + $scope.user.list.keeper.id, "POST");
            if (staffDelRe.code == 200) { //
                $scope.user.list.keeper = null;
            } else { //
                errorMsg(staffDelRe);
            }
        }
    })
    /*------------------------------------------------------------------*/
app.controller('StaffaddCtr', function($scope, $location, $routeParams) {
    $scope.show = {};
    $scope.posts = {};
    $scope.staffadd_form = {};
    $scope.config.breadset = [{ //
        name: "员工管理",
        href: indexUrl + "/admin.html#/staff"
    }, {
        name: "添加员工"
    }]; //面包屑
    $scope.shopsget = ajaxSendFn({}, "/shops/shop/" + $routeParams.shopId, "GET").result;
    $scope.textCheckJson = textCheckJson;
    $scope.textCheckErrorJson = textCheckErrorJson;
    $scope.staffadd_form.submitted = false;
    $scope.posts.gender = 0;
    $scope.shopId = $routeParams.shopId;
    $scope.staffaddsend = function(keeper) { //
        $scope.posts.shopId = $routeParams.shopId;
        $scope.posts.roleType = keeper == "keeper" ? "K" : "S";
        $scope.posts.password = hex_md5($scope.posts.password);
        sendJson = JSON.stringify($scope.posts);
        result = ajaxSendFn(sendJson, constUrlDict["staff"], "POST", 1);
        if (result.code == 200) { //
            alert("添加成功");
            $location.path("/staff/show/" + $routeParams.shopId);
        }else {
            errorMsg(result);
        }
    }
})
app.controller('StaffeditCtr', function($scope, $location, $routeParams, $http) {
    $scope.posts = {};
    $scope.staffadd_form = {};
    $scope.config.breadset = [{ //
        name: "员工管理",
        href: indexUrl + "/admin.html#/staff"
    }, {
        name: "编辑员工"
    }]; //面包屑
    $scope.staffget = ajaxSendFn({}, constUrlDict["staff"]+"/" + $routeParams.guestid, "GET").result;
    $scope.staffadd_form.submitted = false;
    $scope.posts.gender = $scope.staffget.gender;
    $scope.posts.nickname = $scope.staffget.nickname;
    $scope.posts.shopId = $scope.staffget.shopId;
    $scope.show = {};
    $http.get(basicUrl + "/shops/shop/" + $scope.staffget.shopId).success(function(data) {
        console.log(data);
        if (data.code == 200) $scope.show.shopname = data.result.name;
    })
    $scope.staffaddsend = function() { //
        $scope.posts.shopId = $scope.staffget.shopId;
        sendJson = JSON.stringify($scope.posts);
        result = ajaxSendFn(sendJson, constUrlDict["staff"] +"/" + $scope.staffget.id, "POST", 1);
        if (result.code == 200) { //
            alert("修改成功");
            $location.path("/staff/show/" + $scope.staffget.shopId);
        }else {
            errorMsg(result);
        }
    }
})
app.controller('passwordCtr', function($scope, $location, $routeParams) {
    $scope.show = {};
    $scope.posts = {};
    $scope.staffadd_form = {};
    $scope.config.breadset = [{ //
        name: "员工管理",
        href: indexUrl + "/admin.html#/Staff"
    }, {
        name: "重设密码"
    }]; //面包屑
    $scope.staffget = ajaxSendFn({}, constUrlDict["staff"]+"/" + $routeParams.guestid, "GET").result;
    $scope.textCheckJson = textCheckJson;
    $scope.textCheckErrorJson = textCheckErrorJson;
    $scope.staffadd_form.submitted = false;
    $scope.staffget.shopname = ajaxSendFn({}, "/shops/shop/" + $scope.staffget.shopId, "GET").result.name;
    $scope.staffaddsend = function() { //
        if (!$scope.staffadd_form.$valid) {
            $scope.staffadd_form.submitted = true;
            return;
        } else { ///
            var json = {};
            angular.extend(json, $scope.posts);
            json.password = hex_md5($scope.posts.password);
            result = ajaxSendFn(json, constUrlDict["staffs-password"] +"/"+ $scope.staffget.id, "POST");
            if (result.code == 200) { //
                alert("修改成功");
                $location.path("/staff/show/" + $scope.staffget.shopId);
            }else {
                errorMsg(result);
            }
        };
    }
})
app.controller('RuleCtr', function($rootScope, $scope, $location, $filter) { //shoplist over
    $scope.config.breadset = [{ //
        name: "活动管理",
        href: indexUrl + "/admin.html#/rule"
    }, {
        name: "活动列表"
    }]; //面包屑
    var rule = ajaxSendFn({}, "/activity", "GET").result || [];
    var lastShow = $rootScope.lastShow;
    $scope.ruleDic={nonParticipations:"不参与活动商品",periods:"有效时段",time:"时间",shops:"分店"};//将key转为中文
    $scope.view = {};
    $scope.view.rule = $filter("orderBy")(rule, "createTime", true);
    if (lastShow != null) {
      $scope.view.rule[lastShow].show = 1;
    }
    for (x in $scope.view.rule) { //定义icon
        var tem = $scope.view.rule[x];
        $scope.view.rule[x].icon = {};
        for (y in tem.rules) {
            tem.rules[y].type = tem.rules[y].type.split("_");
            $scope.view.rule[x].icon[tem.rules[y].type[0]] = 1;
        }
    }
    $scope.pannel = function(nowindex) { //切换显示列表
        if (lastShow != null && lastShow >= 0 && nowindex === lastShow) {
           $scope.view.rule[nowindex].show = 0;
           lastShow = -1;
           delete $rootScope.lastShow;
        }else{
          var id = $scope.view.rule[nowindex]._id;
          if (!$scope.view.rule[nowindex].rulesget) {
              tem = ajaxSendFn({}, "/activity/" + id + "/rules", "GET");
              if (tem.code == 200) $scope.view.rule[nowindex].rulesget = tem.result;
          }
          $.each($scope.view.rule, function(index) {
              $scope.view.rule[index].show = 0;
          });
          $scope.view.rule[nowindex].show = 1;
          lastShow = nowindex;
          $rootScope.lastShow = lastShow;
        }
    }
    $scope.activityOn = function(id, i) { //上线
        re = ajaxSendFn({}, "/activity/" + id + "/on", "PUT");
        if (re.code == 200) $scope.view.rule[i].on = true;
        else errorMsg(re);
    }
    $scope.activityOff = function(id, i) { //下线
        re = ajaxSendFn({}, "/activity/" + id + "/off", "PUT");
        if (re.code == 200) $scope.view.rule[i].on = false;
        else console.error(re);
    }
});
app.controller('RuleAddCtr', function($scope, $location, $filter, $routeParams) { //shoplist over
    $scope.config.breadset = [{ //
        name: "活动管理",
        href: indexUrl + "/admin.html#/rule"
    }, {
        name: "设置活动范围"
    }]; //面包屑

    $scope.checkshop = {};
    $scope.set = {
        times: ajaxSendFn({}, "/businesstimes/all", "GET"). result,
        list: ajaxSendFn({}, "/shops?state=1002", "GET").result,
        list2: [],
        timeType: {
            "1001": "早市",
            "1002": "午市",
            "1003": "下午茶",
            "1004": "晚市",
            "1005": "宵夜"
        },
        periods: [],
    };
    $scope.set.time = getSubtimes($scope.set.times, $scope.set.timeType);
    if (!$scope.set.list) {
        alert("目前还没有添加门店");
        $location.path("/shops");
    }
    $scope.set.nonParticipation = ajaxSendFn({}, "/nonParticipation", "GET").result; //非参与项
    $scope.checkallstr = 0;

    $scope.posts = {
        periods: [],
        excludeWeekend: false,
        excludeHoliday: false,
        shared:[],
        shops:[],
    };
    $scope.view = {
        data:{},
        effectDates:{},
        periods: [],
        zhiding: $scope.config.time
    };
    if ($routeParams.activityid) {
      $scope.view.isEdit = true;
    }else {
      $scope.view.isEdit = false;
    }

    //活动类型
    $scope.ruleCategory = ruleCategory;
    $scope.$watch('posts.activityCategory', function (newVal, oldVal) {
      if (newVal && newVal !== oldVal) {
        $scope.shareRuleCategory = getShareCategory(newVal);
      }
    });
    //过滤活动同享数组，去除空元素
    $scope.filterShared = function () {
      return arrayFilter($scope.posts.shared, function (data) {
        return data ? true : false;
      });
    };
    $scope.checkAllCatagory = function () {
    if(!$scope.posts.catagoryAll) $scope.posts.shared=[];
    else{
        angular.forEach(
            $scope.shareRuleCategory,function (value,key) {
                this[key]=value.id;
            },$scope.posts.shared
        )};
    };
    $scope.categoryName = function (category) {
        var result = {};
        if (category) {
            var tmp = category.split('_')[0];
            angular.forEach($scope.ruleCategory, function (data,idx) {
              if (data.id === category) {
                this.name = data.name;
              }
            },result);
        };
        return result.name || "类型错误";
    }
    $scope.$watch('set.shopAll', function (newVal, oldVal) {
      if (newVal !== oldVal) {
        if (newVal) {
          angular.forEach($scope.set.list,function (value,key) {
              this[key]=value.id;
            },$scope.posts.shops)
        }else {
          $scope.posts.shops=[];
        }
      }
    });
    $scope.settime = function(a, b) { //
        $scope.view.periods[a] = $scope.view.periods[a] ? null : b;
    }

    $scope.sendJsons = function() { //arrRemoveNullFN
		sendtype = $routeParams.activityid ? "EDIT" : "ADD";
        sendid = $routeParams.activityid ? $routeParams.activityid : "";
        $scope.posts.shops = arrRemoveNullFN($scope.posts.shops);
        $scope.posts.periods = arrRemoveNullFN($scope.view.periods);
        var json = {};
        json.nonParticipationId = $scope.posts.nonParticipationId;
        json.shared = uniqArr(arrRemoveNullFN($scope.posts.shared));
        json.name = $scope.posts.name;
        json.activityCategory = $scope.posts.activityCategory;
        json.shops = $scope.posts.shops;
        json.periods = $scope.posts.periods;
        json.excludeWeekend = $scope.posts.excludeWeekend;
        json.excludeHoliday = $scope.posts.excludeHoliday;
        json.dateRangeCategory = $scope.view.data.dateType;
        json.dateRange = {};
        //如果开始时间被修改过，并且小于今天，则报错
        if ($scope.view.data.dateType === "CONTINUOUS") {
          if (!$scope.view.dateRange.startDate || !$scope.view.dateRange.endDate) {
            alert("请填写开始和结束日期!");
            return;
          }
          if ($scope.view.dateRange.endDate < $scope.view.dateRange.startDate) {
            alert("结束日期不能小于开始日期!");
            return;
          }
          else{
            json.dateRange.startDate = $filter("date")($scope.view.dateRange.startDate, "yyyy-MM-dd 00:00:00");
            json.dateRange.endDate = $filter("date")($scope.view.dateRange.endDate, "yyyy-MM-dd 23:59:59");
          }
        }else if($scope.view.data.dateType === "SELECTED_DATES"){
          if (isEmptyObject($scope.view.dateRange.effectDates)) {
            alert("手选日期个数不能为零!")
            return;
          }else{
            json.dateRange.effectDates = [];
            for (var x in $scope.view.dateRange.effectDates) { //
              x = x + " 00:00:00"
              json.dateRange.effectDates.push(x);
            }
          }
        }else if($scope.view.data.dateType === "AROUND_FIX_DATE"){
            json.dateRange.beforeDays = $scope.view.dateRange.beforeDays || 0;
            json.dateRange.afterDays = $scope.view.dateRange.afterDays || 0;
        }else if ($scope.view.data.dateType === "EXCLUDE_MONTH_DAYS") {
            var arr = $scope.view.dateRange.excludeDays.toString().replace(/，/g,',').split(',');
            json.dateRange.excludeDays = arrayMap(arr, parseInt);
        }else if ($scope.view.data.dateType === "INCLUDE_MONTH_DAYS") {
            var arr = $scope.view.dateRange.includeDays.toString().replace(/，/g,',').split(',');
            json.dateRange.includeDays = arrayMap(arr, parseInt);
        }else if ($scope.view.data.dateType === "EXCLUDE_WEEKLY_DAY") {
            json.dateRange.excludeWeekly = arrayMap(objectKeys($scope.view.dateRange.excludeWeekly), parseInt);
        }else if ($scope.view.data.dateType === "INCLUDE_WEEKLY_DAY") {
            json.dateRange.includeWeekly = arrayMap(objectKeys($scope.view.dateRange.includeWeekly), parseInt);
        }else if ($scope.view.data.dateType === "AUTOMATIC_DAY_DELAY") {
            json.dateRange.delayedDays = $scope.view.dateRange.delayedDays || 0;
            json.dateRange.effectDays = $scope.view.dateRange.effectDays || 0;
        }

        sendJson = JSON.stringify(json);
        postsend = ajaxSendFn(sendJson, concatUrl(constUrlDict["activity"], sendid), "POST", 1);
        if (postsend.code == 200) { //
            if (sendtype == "ADD") {
                $location.path("/rule/add2/" + postsend.result.id);
            } else {
                alert("保存成功");
				        history.back();
            }
        } else { //
            errorMsg(postsend);
        }
    }

    $scope.addNonParticipation = function() {
        $scope.goods = "";
        $("#NonParticipation").modal("show");
    }
    $scope.NonParticipationSend = function() {
        send = ajaxSendFn({"items":$scope.goods.name}, "/nonParticipation", "POST", 2);
        if (send.code == 200) { //
            if (!$scope.set.nonParticipation) {
                $scope.set.nonParticipation = {};
            };
            $scope.set.nonParticipation._id = send.result;
            $scope.set.nonParticipation.items = $scope.goods.name;
            $("#NonParticipation").modal("hide");
        }
    }
    $scope.oldFN = function() { //获取旧的内容
        var tem = ajaxSendFn({}, concatUrl(constUrlDict["activity"], $routeParams.activityid)+"/detail", "GET").result;
        if (!tem) return;

        //$scope.date.join=tem.effectDates;
        $scope.posts.name = tem.name;
        $scope.posts.hasRules = (tem.rules && tem.rules.length > 0) || false;
        $scope.posts.activityCategory = tem.activityCategory;
        $scope.view.data.dateType = tem.dateRangeCategory;
        $scope.view.dateRange = tem.dateRange;
        if ($scope.posts.activityCategory) {
              $scope.shareRuleCategory = getShareCategory($scope.posts.activityCategory);
        }
        $scope.posts.excludeHoliday = tem.excludeHoliday;
        $scope.posts.excludeWeekend = tem.excludeWeekend;
        $scope.posts.nonParticipationId = tem.nonParticipationId;
        var temShops = {};
        if (tem.shops) {
            for (var i = 0, j = tem.shops.length || 0; i < j; i++) {
                temShops[tem.shops[i]] = 1;
            }
        };

        for (var i = 0, j = $scope.set.list.length || 0; i < j; i++) {
            if ($scope.set.list[i].id in temShops) $scope.posts.shops[i] = $scope.set.list[i].id;
        }
        angular.forEach($scope.set.time, function (data, idx) {
          this.push(idx);
        },$scope.view.periods);

        angular.forEach($scope.view.periods, function (data, idx) {
          if (tem.periods.indexOf(data) == -1) {
            this[idx] = null;
          }
        },$scope.view.periods);

        angular.forEach($scope.shareRuleCategory, function (data, idx) {
            if (tem.shared && tem.shared.indexOf(data.id) != -1) {
                this[idx] = data.id;
            }else{
                this[idx] = false;
            }
        }, $scope.posts.shared);
    }
    if ($routeParams.activityid) $scope.oldFN();
});
app.controller('RuleDISCOUNTCtr', function($scope) { //shoplist over
    $scope.DISCOUNT.posts = {
        type: "DISCOUNT"
    };
    $scope.DISCOUNT.posts.detail = [];
    $scope.DISCOUNT.addFn = function() {
        $scope.DISCOUNT.posts.detail.push({
            menber: $scope.view.menber[0].id
        });
    }
    $scope.DISCOUNT.removeFn = function(i) {
        $scope.DISCOUNT.posts.detail.splice(i, 1);
    }
    $scope.DISCOUNT.addFn();
});
app.controller('RuleLIMITCtr', function($scope, $location) { //shoplist over
    $scope.LIMIT.posts = {
        type: "LIMIT_PREMENT"
    };
    $scope.LIMIT.posts.detail = [];
    $scope.LIMIT.addFn = function() {
        console.log($scope.LIMIT.posts)
        $scope.LIMIT.posts.detail.push({
            menber: $scope.view.menber[0].id
        });
    }
    $scope.LIMIT.removeFn = function(i) {
        $scope.LIMIT.posts.detail.splice(i, 1);
    }
    $scope.LIMIT.addFn();
});
app.controller('RulEspendasCtr', function($scope, $location) { //折扣
    $scope.SPEND.posts = {
        type: "SPEND"
    };
    $scope.SPEND.posts.detail = [];
    $scope.SPEND.addFn = function() {
        console.log($scope.SPEND.posts)
        $scope.SPEND.posts.detail.push({
            menber: $scope.view.menber[0].id
        });
    }
    $scope.SPEND.removeFn = function(i) {
        $scope.SPEND.posts.detail.splice(i, 1);
    }
    $scope.SPEND.addFn();
});
app.controller('RulSpecialpriceCtr', function($scope, $location) { //折扣
    $scope.SPECIAL.posts = {
        type: "SPECIAL"
    };
    $scope.SPECIAL.posts.detail = [];
    $scope.SPECIAL.addFn = function() {
        console.log($scope.SPECIAL.posts)
        $scope.SPECIAL.posts.detail.push({
            menber: $scope.view.menber[0].id
        });
    }
    $scope.SPECIAL.removeFn = function(i) {
        $scope.SPECIAL.posts.detail.splice(i, 1);
    }
    $scope.SPECIAL.addFn();
});
app.controller('RulCHARGECtr', function($scope, $location) { //
    $scope.CHARGE.check = [];
    $scope.CHARGE.addFn = function(a) {
        $scope.CHARGE[a].posts.detail.push({
            menber: $scope.view.menber[0].id
        });
    }
    $scope.CHARGE.removeFn = function(a, i) {
        $scope.CHARGE[a].posts.detail.splice(i, 1);
    }
    var type = ["CHARGE_PREMENT", "CHARGE_POINT", "CHARGE_COUPON", "CHARGE_GIFT"];
    for (var i = 0; i < type.length; i++) {
        $scope.CHARGE[i] = {
            posts: {
                detail: [],
                type: type[i]
            }
        };
        $scope.CHARGE.addFn(i);
    }
});
app.controller('RulPointCtr', function($scope, $location) { //shoplist over
    $scope.POINT.posts = {
        type: "POINT",
        detail: []
    };
    $scope.POINT_CONSUME.posts = {
        type: "POINT_CONSUME",
        detail: []
    };
    $scope.POINT_GIFT.posts = {
        type: "POINT_GIFT",
        detail: []
    };
    $scope.POINT_COUPON.posts = {
        type: "POINT_COUPON",
        detail: []
    };
    $scope.POINT.addFn = function(a) {
        $scope[a].posts.detail.push({
            menber: $scope.view.menber[0].id
        });
    }
    $scope.POINT.removeFn = function(a, i) {
        $scope[a].posts.detail.splice(i, 1);
    }
    $scope.POINT.addFn('POINT');
    $scope.POINT.addFn('POINT_CONSUME');
    $scope.POINT.addFn('POINT_GIFT');
    $scope.POINT.addFn('POINT_COUPON');
});
app.controller('RuleMemberCtr', function($scope, $filter) {
    $scope.config.breadset = [{ //
        name: "活动管理",
        href: indexUrl + "/admin.html#/rule"
    }, {
        name: "会员规则管理"
    }]; //面包屑
    $scope.plan = {
        add: 0
    };
	$scope.upgradeType = {
		"CUSTOMER":"CUSTOMER",
		"MEMBER":"MEMBER",
	};
    temMemberGet = ajaxSendFn({}, "/memberGrade", "GET").result || [];
    $scope.view = {
        menber: $filter('orderBy')(temMemberGet, "grade", false),
        plan: {},
        isUpdate: false,
        maxGrades:6, //级别数量
    };

    $scope.posts = [];
    $scope.check = {};
    // $('[data-toggle="tooltip"]').tooltip()
    $scope.closeModal = function () {
      $scope.view.menber[$scope.view.plan.level-1].name = $scope.oldGradeName;
      $scope.view.isUpdate = false;
      $("#memberadd").modal("hide");
    }
    $scope.handleClick = function (a) {
      if (!$scope.view.isUpdate) {
        $scope.addplan(a);
      }else {
        $scope.updatePlan(a);
      }
    }
    $scope.validateName = function (a, name) {
      var isInvalid = false;
      angular.forEach($scope.view.menber, function (value, idx) {
        if (!isInvalid) {
          if (idx != a - 1 && name === value.name) {
              isInvalid = true;
          }
        }
      });
      return isInvalid;
    }
    $scope.addnewFn = function(a) {
        $scope.tem = {};
        $scope.planform.memberName.$touched = false;
        $scope.view.plan.level = $scope.view.menber.length + 1;
        $("#memberadd").modal("show");
    };
    $scope.updateFn = function (a) {
        $scope.tem = $scope.view.menber[a - 1];
        $scope.oldGradeName = $scope.tem.name;
        $scope.view.isUpdate = true;
        $scope.view.plan.level = a;
        $("#memberadd").modal("show");
    }
    $scope.switchStatus = function (bool) {
        var str = bool===true ? "on" : "off";
        var res = ajaxSendFn({}, "/memberUpgrade/"+str, "POST");
        if (res.code != 200) {
            errorMsg(res);
        }else{
            var astr = str === "on" ? "启用" : "停用";
            alert("您已成功"+ astr +"会员计划");
        }
    }
    $scope.addplan = function(a) {
        send = ajaxSendFn({
            name: $scope.tem.name
        }, "/memberGrade", "POST");
        if (send.code == 200) { //
            $scope.tem.id = send.result;
            $scope.view.menber[$scope.view.menber.length] = {
                name: $scope.tem.name,
                id: $scope.tem.id,
                grade: $scope.view.menber.length + 1
            };
            $scope.view.show = {
                name: $scope.tem.name,
                grade: $scope.view.menber.length - 1
            };
            $scope.posts = [];
            $("#memberadd").modal("hide");
            $scope.showFn($scope.view.menber.length);
        }else{
          errorMsg(send);
        }
        $scope.plan = {
            add: 1
        };
    }
    $scope.updatePlan = function (a) {
        if ($scope.validateName(a, $scope.tem.name) || $scope.tem.name === $scope.oldGradeName) {
            alert("新级别名称不能重复");
            return;
        }
        send = ajaxSendFn({name:$scope.tem.name}, "/memberGrade/"+ $scope.tem.id, "POST");
        if (send.code == 200) {
            $scope.view.menber[a-1].name = $scope.tem.name;
            $("#memberadd").modal("hide");
            $scope.view.isUpdate = false;
        }else {
            $scope.view.menber[a-1].name = $scope.oldGradeName;
            errorMsg(send);
        }
    }
    $scope.closeFn = function(a) {
        $scope.plan[a] = 0;
    };
    $scope.showFn = function(a) {
        $scope.view.show = $scope.view.menber[a - 1];
        if (!$scope.view.menber[a - 1].Upgrade) $scope.view.menber[a - 1].Upgrade = ajaxSendFn({}, "/memberUpgrade/toId/" + $scope.view.menber[a - 1].id, "GET").result || [];
        $scope.posts = {};
        $scope.check = {};
        for (x in $scope.view.menber[a - 1].Upgrade) {
            type = $scope.view.menber[a - 1].Upgrade[x].type;
            if (!$scope.posts[type]) {
                $scope.posts[type] = {};
            }
            $scope.posts[type]._id = $scope.view.menber[a - 1].Upgrade[x]._id;
            fromid = $scope.view.menber[a - 1].Upgrade[x].fromId;
            //如果从一般顾客升级到第1级会员
            if (fromid === $scope.upgradeType["CUSTOMER"] && a === 1) {
                $scope.posts[type].value = $scope.view.menber[a - 1].Upgrade[x].value;
            //如果从一般顾客直接升级到大于1级的会员，即跨级别升级
            }else if (fromid === $scope.upgradeType["CUSTOMER"] && a > 1) {
                $scope.posts[type].special_value = $scope.view.menber[a - 1].Upgrade[x].value;
                if (type === "POINT") {
                  $scope.posts[type].value = $scope.view.menber[a - 1].Upgrade[x].value;
                }
            //其他情况，按步就班升级，如1到2，2至3，3至4等
            }else{
                $scope.posts[type].value = $scope.view.menber[a - 1].Upgrade[x].value;
            }

            $scope.check[type] = true;
        }
        $scope.plan = {
            add: 1
        };
    }
    $scope.postSend = function() {//提交表单，添加、修改会员升级规则
        var json = [];
        toid = $scope.view.menber[$scope.view.show.grade - 1].id;
        for (var x in $scope.posts) {
            if (x !== 'BUY' && !$scope.check[x]) {
              continue;
            }
            //如果规则的value有效
            _id = $scope.posts[x]._id;
            if ($scope.posts[x] && $scope.posts[x].value != null || x == "FREE") {
                var send = {};
                _id && (send._id = _id);
                send.type = x;
                send.toId = toid;
                var fromid;
                if ($scope.view.show.grade <= 1) {
                    formid = $scope.upgradeType["CUSTOMER"];
                } else {
                    formid = $scope.view.menber[$scope.view.show.grade - 2].id;
                }
                send.fromId = formid;
                if (x != "FREE") {
                    send.value = $scope.posts[x].value;
                }
                json.push(send);
            }
            //如果规则的special_value有效
            if ($scope.posts[x].special_value != null) {
                var send = {};
                _id && (send._id = _id);
                send.type = x;
                send.toId = toid;
                send.fromId = $scope.upgradeType["CUSTOMER"];
                send.value = $scope.posts[x].special_value;
                json.push(send);
            }
        }
        re = ajaxSendFn(JSON.stringify(json), "/memberUpgrade/"+toid, "POST", 1);
        if (re.code == 200) {
            $scope.plan.add = 0;
            $scope.view.menber[$scope.view.show.grade - 1].Upgrade = ajaxSendFn({}, "/memberUpgrade/toId/" + toid, "GET").result || [];
        } else {
            errorMsg(re);
        }
    }
});
app.controller('RuleCouponOFFSETCASHCtr', function($scope) { //
    /*
		$scope.OFFSETCASH.addFn=function (a) {
			$scope.OFFSETCASH.post[a].push({menber:$scope.view.menber[0]});
		}
		$scope.OFFSETCASH.removeFn=function (a,i) {
			$scope.OFFSETCASH.post[a].splice(i,1);
			console.log($scope.OFFSETCASH.post[a]);
		}
		$scope.OFFSETCASH.addFn();
	*/
});
app.controller('CustomerCtr', function($scope, tyFnFactory, $http) { //
    $scope.config.breadset = [{ //
        name: "顾客管理",
        href: indexUrl + "/admin.html#/customer"
    }, {
        name: "顾客列表"
    }]; //面包屑
    $scope.dict = {
        source: {
            9001: "上宾",
            9002: "手动"
        },
        cardType: {
            "v_card": "电子卡",
            "p_card": "实物卡",
            "b_card": "绑定卡"
        },
        memberType: [{
            name: "所有顾客",
            key: ""
        }, {
            name: "会员",
            key: "MEMBER"
        }]
    };
    $scope.view = {
        interest: {}
    };
    $http.get(basicUrl + constUrlDict["customer"]).success(function(data) {
        $scope.view.customer = data.result || [];
    })
    $scope.view.member = [];
    $scope.search = {
        type: $scope.dict.memberType[0].key
    };
    $http.get(basicUrl + constUrlDict["memberGrade"]).success(function(data) {
        if (!data.result || !data.result.items) return;
        for (var i = 0, j = data.result.items.length; i < j; i++) { //
            $scope.view.member[data.result.items[i].grade] = data.result.items[i];
        }
    })
    $scope.postSend = function() {
        $scope.view.customer = ajaxSendFn($scope.search, constUrlDict["customer"], "GET").result || [];
    }
    $scope.interestGetFn = function(a) {
        if (!$scope.view.interest[a]) $scope.view.interest[a] = ajaxSendFn({}, constUrlDict["benefit"]+"?userId=" + a, "GET").result || [];
    }
    $scope.pageChange = function() {
        $scope.search.page = $scope.view.customer.page;
        $scope.postSend();
    }
});
app.controller('CustomerChargeCtr', function($scope, $routeParams, $filter, $http) { //
    $scope.config.breadset = [{ //
        name: "顾客管理",
        href: indexUrl + "/admin.html#/customer"
    }, {
        name: "顾客充值"
    }]; //面包屑
    $scope.view = {};
    $scope.posts = {
        type: 'PUT'
    };
    $scope.reason = {
        "PUT": "使用",
        "POST": "充值"
    };
    $http.get(basicUrl + constUrlDict["customer"]+"/" + $routeParams.userId).success(function(data) {
        console.log(data)
        $scope.view.user = data.result || []
    })
    $http.get(basicUrl + "/interest?userId=" + $routeParams.userId).success(function(data) {
        $scope.view.interest = data.result || []
    })
    $scope.send = function() {
        json = {};
        json.users = $routeParams.userId;
        json.charge = $scope.posts.charge;
        json.reason = "GIVE_FREE";
        reason = $scope.reason[$scope.posts.type];
        re = ajaxSendFn(JSON.stringify(json), "/interest", $scope.posts.type, 1);
        if (re.code == 200) {
            $scope.view.interest = ajaxSendFn({}, "/interest?userId=" + $routeParams.userId, "GET").result || [];
            $scope.posts.charge = 0;
            alert(reason + "成功");
        } else {
            errorMsg(re);
        };
    }
});
app.controller('CustomerPoicustomerntCtr', function($scope, $routeParams) { //
    $scope.view = {
        user: ajaxSendFn({}, constUrlDict["customer"]+"/" + $routeParams.userId, "GET").result || []
    };
    $scope.posts = {
        type: 'PUT'
    };
    $scope.reason = {
        "PUT": "使用",
        "POST": "发放"
    };
    $scope.view.interest = ajaxSendFn({}, "/interest?userId=" + $routeParams.userId, "GET").result || [];
    $scope.send = function() {
        console.log($scope.posts)
        json = {};
        json.users = $routeParams.userId;
        json.point = $scope.posts.point;
        json.reason = "GIVE_FREE";
        reason = $scope.reason[$scope.posts.type];
        re = ajaxSendFn(JSON.stringify(json), "/interest", $scope.posts.type, 1);
        if (re.code == 200) {
            $scope.view.interest = ajaxSendFn({}, "/interest?userId=" + $routeParams.userId, "GET").result || [];
            $scope.posts.point = 0;
            alert(reason + "成功");
        } else {
            errorMsg(re);
        };
    }
});
app.controller('CustomerCouponCtr', function($scope, $routeParams) { //
    $scope.view = {
        user: ajaxSendFn({}, constUrlDict["customer"]+"/" + $routeParams.userId, "GET").result || []
    };
    $scope.view.coupons = ajaxSendFn({}, constUrlDict["coupon"], "GET").result || [];
    $scope.posts.coupons = [$scope.view.coupons[0]._id];
    $scope.add = function() {
        $scope.posts.coupons.push($scope.view.coupons[0]._id);
    }
    $scope.remove = function(a) {
        $scope.posts.coupons.splice(a, 1);
    }
    $scope.send = function() {
        json = {};
        json.users = $routeParams.userId;
        json.coupons = $scope.posts.coupons.join();
        console.log($scope.posts.coupons)
        json.reason = "GIVE_FREE";
        json.couponCount = $scope.posts.count;
        console.log(json)
        re = ajaxSendFn(JSON.stringify(json), "/interest", "POST", 1);
        if (re.code == 200) {
            $scope.view.interest = ajaxSendFn({}, "/interest?userId=" + $routeParams.userId, "POST", 1).result || [];
            $scope.posts.point = 0;
            alert("增券成功");
        } else {
            errorMsg(re);
        };
    }
});
app.controller('CustomerAddCtr', function($scope) { //
    $scope.view = {
        member: ajaxSendFn({}, "/memberGrade", "GET").result || []
    };
    $scope.posts = {
        gender: $scope.view.member[0].gender
    };
    $scope.send = function() {
        re = ajaxSendFn(JSON.stringify($scope.posts), "/customer/guest/GIVE", "POST", 1);
        if (re.code == 200) {
            alert("添加成功");
        } else {
            errorMsg(re);
        };
    }
});
app.controller('RuleAdd2Ctr',['$scope', '$location', '$filter', '$routeParams','CouponFactory', function($scope, $location, $filter, $routeParams, couponFac) { //shoplist over
    $scope.config.breadset = [{ //
        name: "活动管理",
        href: indexUrl + "/admin.html#/rule"
    }, {
        name: "修改活动详情"
    }]; //面包屑;
    $scope.btnDisable=0;
    $scope.today = $filter('date')(new Date(), "yyyy-MM-dd");
    $scope.tem = {
        rules: {}
    };
    $scope.coupon = {
        shared:[],
        shops: []
    };
    $scope.posts = {
    	coupons:{},
    };
    $scope.transferMap = {
      POINT_CONSUME:"POINTCONSUME",
      COUPON_FREE:"COUPONFREE",
      CHARGE_CONSUME:"CHARGECONSUME",
    };
    $scope.transferMapRev = {
      POINTCONSUME:"POINT_CONSUME",
      COUPONFREE:"COUPON_FREE",
      CHARGECONSUME:"CHARGE_CONSUME",
    };

    // $scope.isOpenOrClose = true;
    $scope.temcoupons2={};
    $scope.temcoupons=[];
    $scope.obtainRepeatCategory = obtainRepeatCategory;
    $scope.ruleFn = {
        openOrClose:function(){
            $scope.isOpenOrClose = !$scope.isOpenOrClose;
        },
        testAddOk:function () {
            console.log('OK');
            $scope.isOpenOrClose = false;
            $scope.view.coupons = couponFac.getAllCoupon();
        },
        testAddFail:function (result) {
            console.log("错误编号:"+ result.code +", 错误信息:"+result.message);
            errorMsg(result);
        },
        getCpouponFn: function() {
            $scope.view.coupons = ajaxSendFn({}, "/coupon", "GET").result || [];
        },
        getCouponType:function  (id) {
            for (var i = 0; $scope.view.coupons && i < $scope.view.coupons.length; i++) {
                  if ($scope.view.coupons[i].id === id) {
                     return $scope.view.coupons[i].category;
                  }
              };
        },
        changeCoupon:function (value, dv) {
            if (dv.id) {
                dv.count=1;
                for (var i = 0; i < $scope.view.coupons.length; i++) {
                    if ($scope.view.coupons[i].id === dv.id){
                        dv.name = $scope.view.coupons[i].name;
                        break;
                    }
                };
            }
        },

        oldRuleFn: function() { //从服务器获取目前的规则列表
            var ruletem = ajaxSendFn({}, "/activity/" + $routeParams.activityid + "/detail", "GET").result;
            $scope.ruleFn.getCpouponFn();
            ruletem.activityCategory && ($scope.tem.activityCategory = ruletem.activityCategory.split('_')[0]);
            $scope.view.shop = ajaxSendFn({}, "/shops?state=1002", "GET").result || [];
            $scope.tem.shops = [];
            for (var x in $scope.view.shop) $scope.tem.shops.push($scope.view.shop[x].id);
            if (!ruletem || !ruletem.rules) return;
            $scope.tem.rules = arrToObj(ruletem.rules, "type", "id");
            var oldrules = ajaxSendFn({}, "/rule/ids?ids=" + obj2Array(ruletem.rules, "id").join(), "GET").result || null;
            if (oldrules) { //
                $scope.btnDisable=1;//假如有旧规则,就不可以添加新规则
                for (i = 0, j = oldrules.length; i < j; i++){
                  var type = oldrules[i].type;
                  if ($scope.transferMap.hasOwnProperty(type)) {
                    oldrules[i].type = $scope.transferMap[type];
                  }
                  $scope.ruleFn.stateFn(oldrules[i].type, "show", 1, oldrules[i]);
                }
            }
        },
        stateFn: function(a, b, c, d) { //key,state,show,点击添加规则时调用
            var aRe = a.split("_")[0];
            if (aRe in $scope.view.rules) {
                $scope.view.rules[aRe].state = b;
                $scope.view.rules[aRe].show = c;
            }
            if (b == "add") $scope.ruleFn.buttonFn(a, b);
            if (!d) {//只让添加一项,就让设定活动内容按钮灰掉,d无值表示是手动点击
                $scope.btnDisable=1;
                return;
            }
            var  tem = d.type;
            if (c) $scope.view.rules[aRe].content[tem] = d;
        },
        closeFn: function(a) { //取消按钮
            if ($scope.view.rules[a].state == "edit") { //保存
                $scope.view.rules[a].state = "show";
            } else if ($scope.view.rules[a].state == "add") { //新增
                $scope.view.rules[a].state = "show";
            }
        },
        buttonFn: function(a) { //活动保存按钮
            if ($scope.view.rules[a].state == "show") { //修改
                $scope.ruleFn.postFn(a);
                $scope.view.rules[a].state = "edit";
            } else if ($scope.view.rules[a].state == "edit") { //保存
                var res = $scope.view.rules[a].postFunc(a);
                if (res) {
                    $scope.view.rules[a].state = "show";
                }
            } else if ($scope.view.rules[a].state == "add") { //新增
                for (x in $scope.view.rules[a].content) $scope.view.rules[a].addFunc(x);
                $scope.view.rules[a].state = "edit";
                $("#showadd").modal("hide");
            }
        },
        memberFn: function() {//会员获取
            $scope.view.member = ajaxSendFn({}, "/memberGrade", "GET").result || [];
			      $scope.view.member = $filter('orderBy')($scope.view.member, 'grade');
            $scope.view.member.push({
                id: "CUSTOMER",
                name: "全员"
            }, {
                id: "MEMBER",
                name: "所有会员"
            });
        },
        postFn: function(a) {//发送数据
            var tem = $scope.view.rules[a].content;
            $scope.posts[a] = {};
            for (x in tem) {
                var needCheck = true;
                $scope.posts[a][x] = tem[x];
                if (tem[x] instanceof Array) {
                  needCheck = false;
                }
                $scope.posts[a][x].check = needCheck;
                if (!tem[x].detail || !Object.keys(tem[x].detail).length) {
                    $scope.view.rules[a].addFunc(x);
                }
            }
        },
        addCouponFn:function (x) {
            $scope.ruleFn.addFn(x, function (a,b) {
              if (a === "COUPON"|| b === "COUPON" || x === "COUPONFREE"){
                var arr = $scope.posts[a][x].detail.CUSTOMER;
                if (arr && arr.length > 0 && !isEmptyObject(arr[0])) {
                  var obj = {};
                  obj.value = [{}];
                  $scope.posts[a][x].detail.CUSTOMER.push(obj);
                }else{
                  var obj = $scope.posts[a][x].detail.CUSTOMER[0];
                  obj.value = [{}];
                }
              }
            })
        },
        addFn: function(x, cb) { //
           var cnt = 0;
           var  a, b;
           var arr = x.split("_");
           if (arr && arr.length > 0) {
              a = arr[0];
           }
           if (arr && arr.length > 1) {
             b = arr[1];
           }
            if (!$scope.posts[a] || !$scope.posts[a][x] || !$scope.posts[a][x].detail || isEmptyObject($scope.posts[a][x].detail)) {
                if (!$scope.posts[a]) $scope.posts[a] = {};
                $scope.posts[a][x] = $scope.view.rules[a].content[x];
                if (!$scope.posts[a][x].detail || isEmptyObject($scope.posts[a][x].detail)) $scope.posts[a][x].detail = {
                    "CUSTOMER": [{}],
                };
                if (cb) cb(a, b);
                return;
            };
            if ($scope.posts[a][x].detail.CUSTOMER){
                var obj = {};
                if (cb) {
                  cb(a,b);
                }else{
                  $scope.posts[a][x].detail.CUSTOMER.push(obj);
                }
            }else{
              $scope.posts[a][x].detail.CUSTOMER = [{}];
              if (cb) cb(a, b);
            }
        },
        removeFn: function(x, b, c) {
           var  a = x.split("_")[0];
            if ($scope.posts[a][x].detail[b][c]) $scope.posts[a][x].detail[b].splice(c, 1);
        },
        // 检查券id是否重复和券类型是否重复
        checkCouponList:function (values) {
            for (var i = 0; values && i < values.length - 1; i++) {
                for (var j = i+1; j < values.length; j++) {
                    if (values[i].id === values[j].id) {
                        return true;
                    };
                };
            };

            for (var i = 0; values && i < values.length - 1; i++) {
                var oldtype = $scope.ruleFn.getCouponType(values[i].id);
                for (var j = 1; j < values.length; j++) {
                    var newType = $scope.ruleFn.getCouponType(values[j].id);
                    if (oldtype === newType) {
                        return true;
                    };
                };
            };
            return false;
        },
        //
        sendChargeConsumeFn:function (a) {
          return $scope.ruleFn.sendFn(a, undefined, undefined, function (json) {
            var obj = json.detail.CUSTOMER[0];
            if (!obj.value) {
              obj.value = false;
            }
            obj.amount = 1;
            obj.currentAmount = obj.count = 0;
          });
        },
        sendCouponFn:function (a) {
         return $scope.ruleFn.sendFn(a, function (x, tem2) {
            if (x === "COUPON") {
              for (var key in tem2) {
                if (tem2[key] && tem2[key].length > 0 && $scope.ruleFn.checkCouponList(tem2[key][0].value)) {
                  return {message:"券或券类型不能重复"};
                }
              }
            }
          }, function (b, json) {
            if (b && b === "COUPON" ) {
              for (var key in json.detail) {
                var cache = {};
                for(var item in json.detail[key]){
                  if (cache[key] !== json.detail[key][item].value[0].id) {
                    cache[key] = json.detail[key][item].value[0].id;
                  }else{
                    return {message:"注意：券不能重复"};
                  }
                }
              }
            }
          });
        },
        sendFn: function(a, beforeValidateFunc, afterValidateFunc, fixFunc) { ///没搞完，发送规则
            var tem = $scope.posts[a];
            //整理，删除不需要的规则
            for (var x in tem) {
              if (!$scope.view.rules[a].uncheck) {
                  if (!tem[x].check) {
                      if ($scope.tem.rules && $scope.tem.rules[x]) delete $scope.tem.rules[x];
                      if ($scope.view.rules[a].content[x]) {
                        $scope.view.rules[a].content[x].detail = [];
                        $scope.view.rules[a].content[x].check = false;
                      }
                  }
              }
            }
            //遍历有效规则，提交到服务器
            for (var x in tem) {
                if (!$scope.view.rules[a].uncheck) {
                    if (!tem[x].check) {
	                        continue;
						            }
                }
                var json = {};
                if ($scope.transferMapRev.hasOwnProperty(x)) {
                  json.type = $scope.transferMapRev[x];
                }else {
                  json.type = x;
                }
                json.detail = {};

                tem[x].amountLimit && (json.amountLimit = tem[x].amountLimit);
                tem[x].celling && (json.celling = tem[x].celling);
                tem[x].countLimit && (json.countLimit = tem[x].countLimit);
                tem[x].timesLimit && (json.timesLimit = tem[x].timesLimit);
                tem[x].obtainCategory && (json.obtainCategory = tem[x].obtainCategory);

                var tem2 = tem[x].detail;
                if (beforeValidateFunc && typeof(beforeValidateFunc) === "function") {
                  var obj = beforeValidateFunc(x, tem2);
                  if (obj) {
                    alert(obj.message);
                    return false;
                  }
                }

                var  b;
                var arr = x.split("_");
                if (arr && arr.length > 1) {
                  b = arr[1];
                }

                for (z in tem2) {
                    for (w in tem2[z]) {
                        var tem3 = tem2[z][w],json2 = {};
                        tem3.amount && (json2.amount = tem3.amount);
                        tem3.value && (json2.value = tem3.value);
                        tem3.count && (json2.count = tem3.count);
                        tem3.currentAmount && (json2.currentAmount = tem3.currentAmount);
                        if (json.detail[tem3.id]) json.detail[tem3.id].push(json2);
                        else json.detail[tem3.id] = [json2];
                    }
                }

                if (afterValidateFunc && typeof(afterValidateFunc) === "function") {
                  obj = afterValidateFunc(b, json);
                  if (obj) {
                    alert(obj.message);
                    return false;
                  }
                }
                if (fixFunc && typeof(fixFunc) === "function") {
                  fixFunc(json);
                }

                var postsend = ajaxSendFn(angular.toJson(json), "/rule", "POST", 1);
                if (postsend.code == 200) { //
                    $scope.tem.rules[x] = postsend.result;
                    newjson = obj2Array($scope.tem.rules);
                    rulesend = ajaxSendFn(JSON.stringify(newjson), "/activity/" + $routeParams.activityid + "/rules", "POST", 1);
                    if (rulesend.code == 200) {
                        rulere = ajaxSendFn({}, "/rule/ids?ids=" + postsend.result, "GET").result || null;
                        $scope.view.rules[a].content[x] = rulere[0];
                    }
                }else {
                   errorMsg(postsend);
                   return false;
                }
            }
            return true;
        },
        addCouponPlanFn: function(a) {
            if (a != "new") return;
            $scope.ruleFn.showCouponPlanFn();
        },
        addRuleFn: function() { //显示添加面板
            $scope.view.modal = {
                title: "添加活动内容",
                html: "addrule"
            };
            $("#showadd").modal("show");
        },
        showCouponPlanFn: function(a) {
            $scope.view.modal = {
                title: "添加券",
                html: "couponNew"
            };
            $("#showadd").modal("show");
        },

        put:function(details, dv){
                if (!details.value) {
                    details.value = [];
                };
                dv = {};
                details.value.push(dv);
        },
		resetCouponCntFn:function(details,dv){
            angular.forEach(details.value, function(data,idx){
                if (data && data.id === dv.id) {
                    this.splice(idx, 1);
                };
            }, details.value);
		},
        containsCoupon:function(details,id){
            var tmpIdx = -1;
            for (var i = 0; details.value && i < details.value.length; i++) {
                if(details.value[i].id === id){
                    tmpIdx = i;
                    break;
                }
            };
            return tmpIdx;
        },
    };
    $scope.view = {
        rules: {
            "DISCOUNT": {
                name: "打折",
                uncheck: true,
                state: "",
                show: 0,
                addFunc:$scope.ruleFn.addFn,
                postFunc:$scope.ruleFn.sendFn,
                content: {
                    DISCOUNT: []
                }
            },
            // "LIMIT": {
            //     name: "满赠",
            //     uncheck: true,
            //     state: "",
            //     show: 0,
            //     content: {
            //         LIMIT_PREMENT: []
            //     }
            // },
      /*
            "SPEND": {
                name: "抵扣",
                uncheck: true,
                state: "",
                show: 0,
                content: {
                    SPEND_AS: []
                }
            },*/
            "SPECIAL": {
                name: "特价",
                uncheck: true,
                state: "",
                show: 0,
                addFunc:$scope.ruleFn.addFn,
                postFunc:$scope.ruleFn.sendFn,
                content: {
                    SPECIAL_PRICE: []
                }
            },
            "POINT": {
                name: "消费积分",
                state: "",
                show: 0,
                addFunc:$scope.ruleFn.addFn,
                postFunc:$scope.ruleFn.sendFn,
                content: {
                    POINT: [],
                    POINT_GIFT: [],
                    POINT_COUPON: []
                }
            },
            "POINTCONSUME": {
                name: "积分抵现",
                uncheck: true,
                state: "",
                show: 0,
                addFunc:$scope.ruleFn.addFn,
                postFunc:$scope.ruleFn.sendFn,
                content: {
                  POINTCONSUME: [],
                }
            },
            "CHARGE": {
                name: "充值",
                state: "",
                show: 0,
                addFunc:$scope.ruleFn.addCouponFn,
                postFunc:$scope.ruleFn.sendCouponFn,
                content: {
                    CHARGE_PREMENT: [],
                    CHARGE_POINT: [],
                    CHARGE_GIFT: [],
                    CHARGE_COUPON: []
                }
            },
            "CHARGECONSUME": {
                name: "使用充值卡",
                uncheck: true,
                state: "",
                show: 0,
                addFunc:$scope.ruleFn.addFn,
                postFunc:$scope.ruleFn.sendChargeConsumeFn,
                content: {
                    CHARGECONSUME: [],
                }
            },
            "COUPON": {
                name: "返券活动",
                uncheck: true,
                state: "",
                show: 0,
                addFunc:$scope.ruleFn.addCouponFn,
                postFunc:$scope.ruleFn.sendCouponFn,
                content: {
                    COUPON: [],
                }
            },
            "COUPONFREE": {
                name: "送券活动",
                uncheck: true,
                state: "",
                show: 0,
                addFunc:$scope.ruleFn.addCouponFn,
                postFunc:$scope.ruleFn.sendCouponFn,
                content: {
                    COUPONFREE: [],
                }
            }
        },
        counponType: {
            "OFFSETCASH": "代金券",
            "DISCOUNT": "折扣券",
            "PHYSICAL":"实物券",
            "GIFT": "礼券",
            "new": "新增券",
        }
    }
    $scope.ruleFn.oldRuleFn();
    $scope.ruleFn.memberFn();
    $scope.ruleFn.getCpouponFn();
    if ($scope.tem && $scope.tem.activityCategory && isEmptyObject($scope.tem.rules)) {
        $scope.ruleFn.stateFn($scope.tem.activityCategory,'add',1)
    }

    $scope.check_all = function() { //
        $scope.checkallstr = !$scope.checkallstr;
        if ($scope.checkallstr) { //
            $scope.coupon.shops = $scope.tem.shops;
        } else { //
            $scope.coupon.shops = [];
        }
    }
}]);
app.controller("edit_passwordCtr", function($scope, $location) {
  $scope.show = {};
  $scope.posts = {};
  $scope.staffadd_form = {};
  $scope.config.breadset = [{
    name: "修改密码"
  }]; //面包屑
  $scope.staffaddsend = function() { //
    if (!$scope.staffadd_form.$valid) {
      $scope.staffadd_form.submitted = true;
      return;
    } else { ///
      if ($scope.pasts.oldPassword === $scope.posts.password) {
        alert("原密码和新密码不能相同");
        return;
      }
      var json = {};
      angular.extend(json, $scope.posts);
      json.oldPassword = hex_md5($scope.posts.oldPassword);
      json.password = hex_md5($scope.posts.password);
      result = ajaxSendFn(json, constUrlDict["staffs-password"], "POST");
      if (result.code == 200) { //
        alert("修改成功");
        $location.path("/");
      }else if (result.code == 4102){
        alert("原密码不匹配，请重试");
      }else {
        errorMsg(result);
      }
    };
  }
})

app.controller("RuleCouponCtr",['$scope', '$http' ,'CouponFactory', function($scope, $http, couponFac) {
    $scope.config.breadset = [{ //
        name: "活动管理",
        href: indexUrl + "/admin.html#/rule"
    }, {
        name: "券管理"
    }]; //面包屑;
    $scope.view = {
        coupons: couponFac.getAllCoupon(),
    };

    $scope.openOrClose = function(){
            $scope.isOpenOrClose = !$scope.isOpenOrClose;
    };
    $scope.testAddOk = function () {
            console.log('OK');
            $scope.isOpenOrClose = false;
            $scope.view.coupons = couponFac.getAllCoupon();
    };
    $scope.testAddFail = function (result) {
            console.log("错误编号:"+ result.code +", 错误信息:"+result.message);
            errorMsg(result);
    };
}]);

app.controller("DevicesCtr", ['$scope', '$http', 'deviceFactory', function($scope, $http, deviceFac) {
    $scope.config.breadset = [{ //
        name: "设备管理",
        href: indexUrl + "/admin.html#/devices"
    }, {
        name: "设备列表"
    }]; //面包屑;
    $scope.search = {count:10};
    $scope.getDevices = function(){
            $scope.view = {
                devices: deviceFac.getAllDevices($scope.search),
            };
    };
    $scope.jihuo = function() {
        deviceFac.jihuo(function (data) {
            $scope.getDevices();
        });
    }
    $scope.pageChange = function() {
        $scope.search.page = $scope.view.devices.page;
        $scope.getDevices();
    }

    $scope.getDevices();
}]);
